﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Com.Seezt.Skins;
using UI.Lib;
using Components;
using UI.Lib.Factory;
using Controls;
using UI.CommonForm;
using UI.Lib.Set;
using UI.StorageManagement;

namespace UI.SellOrder
{
    public partial class FrmOrd3a01Medit : UI.ParentForm.BaseMedit
    {
        private bool isReadOnly = false;

        public FrmOrd3a01Medit(string modulecode, string action, string text, string key)
            : base(modulecode, action)
        {
            InitializeComponent();

            this.Text = text;
            this.Key = key;

            //回写的方法
            this.SaveCallFuntion = "Ord3a00Manager$SaveData"; //保存的方法
            IsAfterSaveCloseWin = false;
            this.allowDtlEmpty = false; //可能用户一次想把全部的记录删除
            this.MaxStateFlag = true;//打开页面后让窗口最大化
            if (!string.IsNullOrEmpty(this.Key))
            {
                LoadData();
                IsAfterSaveCloseWin = true;
            }
            if ("P" == action)
            {
                tspBtnAdd.Visible = false;
                tspBtnDel.Visible = false;
                this.saveDtlDataToServer = false;

                this.tspSave.Text = "审 核";
            }
        }


        protected override void AfterSystemChangeControlState()
        {
            this.tbSummary.Focus("sellercode");
        }

        protected override bool BeforeDtlPopUp(string name, ref string where, ref string[] others)
        {
            if ("productcode" == name || "spno" == name)
            {
                where = string.Format("status ='1' {0} {1}", Context.GetAppKeyWhere("muser", true),
                    "spno" == name ? " AND spno IS NOT NULL " : " ");

                string table = string.Format(@"(
SELECT a.productcode, a.status, a.muser, a.productname, a.bordqty, ISNULL(d.nprice,a.bprice) as bnprice,
ISNULL((CASE WHEN '{0}' = '' THEN (SELECT SUM(storageqty) FROM Sto6a00 z WHERE z.pid = a.listid) ELSE e.storageqty END),0) AS storageqty,
a.listid, taxpct, c.spno, d.promocode, a.pamt, a.umdesc, a.pvlistid
FROM
Pot3a00_view a
LEFT JOIN Bas0a05 b ON a.taxid = b.listid
LEFT JOIN Bas1a13 c ON a.listid = c.pid AND c.slistid = '{2}'
LEFT JOIN Pot4a00 d ON a.listid = d.pid AND datediff(d,d.startdate ,GETDATE()) >= 0 AND  datediff(d,d.endate ,GETDATE()) <= 0 
AND EXISTS(SELECT 1 FROM Pot4a01 e WHERE d.promocode = e.plistid AND e.splistid = '{1}' AND e.slistid ='{2}')
LEFT JOIN Sto6a00 e ON a.listid = e.pid AND e.storageid = '{0}' ) T",
                Validation.ToString(this.tbSummary.GetValue("storageid")),
                Validation.ToString(this.tbSummary.GetValue("splistid")),
                Validation.ToString(this.tbSummary.GetValue("sellerid"))
                );

                others = new string[] { table };
            }

            return true;
        }

        //新增行后触发，用户只读概要
        protected override void AfterAddRow()
        {
            if (isReadOnly == true) return;

            this.tbSummary.Enable("sellercode", false);
            this.tbSummary.Enable("shopcode", false);
            this.tbSummary.Enable("comcode", false);
            this.tbSummary.Enable("addcode", false);
            this.tbSummary.Enable("stocode", false);
        }

        protected override void AfterDelete()
        {
            if (this.dgvDtl.Rows.Count == 0)
            {
                this.tbSummary.Enable("sellercode", true);
                this.tbSummary.Enable("shopcode", true);
                this.tbSummary.Enable("comcode", true);
                this.tbSummary.Enable("addcode", true);
                this.tbSummary.Enable("stocode", true);
                isReadOnly = false;
            }

            double[] sum = CalcDtlAmt();
            this.tbSummary.SetValue("ordamt", sum[0]);
            this.tbSummary.SetValue("dutyamt", sum[1]);
        }

        protected override void AfterSaveData(bool isSuccess)
        {
            if (isSuccess)
            {
                this.tbSummary.Enable("sellercode", true);
                this.tbSummary.Enable("shopcode", true);
                this.tbSummary.Enable("comcode", true);
                this.tbSummary.Enable("addcode", true);
                this.tbSummary.Enable("stocode", true);
                isReadOnly = false;
            }
        }

        protected override void AfterSaveSuccess(Dictionary<string, object> returnData)
        {
            if ("A" == this.Action)
            {
                if (ShopSetting.DirectStock(_lastShopId) && returnData != null && returnData.ContainsKey("id"))
                {
                    var id = returnData["id"].ToString();

                    //提示用户是否要打印
                    if (MsgBox.Show(this, "提示", "是否打印发货单？", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        //转跳到打印页面
                        PrintBtnClick(id);
                    }
                }
            }

            _lastShopId = null;
        }

        private bool _isPrint = false;
        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="listId"></param>
        void PrintBtnClick(string listId)
        {
            string listid = Validation.ToString(listId);
            var frm = new FrmOrdSendPrint();
            frm.AddParam("listid", listid); //添加参数
            frm.Show();

            _isPrint = true;
        }

        protected override void PageInit()
        {
            this.tbSummary.DefaultWidth = 100;
        }

        public override bool BeforePopWin(string name, ref string where, ref string[] others)
        {
            if ("sellercode" == name)
            {
                where = string.Format(" status ='1' {0} ", Context.GetAppKeyWhere("usercode", true));
            }
            else if ("traffcode" == name) //销售商 或者是物流公司名称
            {
                where = Context.GetAppKeyWhere("usercode");
            }
            else if ("typecode" == name) //类别代码
            {
                where = Context.GetAppKeyWhere("muser");
            }
            else if ("shopcode" == name)//门店
            {
                string sellerid = Validation.ToString(this.tbSummary.GetValue("sellerid"));
                if (string.IsNullOrEmpty(sellerid))
                {
                    MessageBox.Show("请先选择销售商！", "提示");
                    this.tbSummary.Focus("sellercode");
                    return false;
                }

                where = string.Format("slistid = '{0}' {1} ", sellerid, Context.GetAppKeyWhere("muser", true));
            }
            else if ("comcode" == name) //公司代码
            {
                where = string.Format("slistid = '{0}' ",
                    Validation.ToString(this.tbSummary.GetValue("sellerid")));
            }
            else if ("addcode" == name) //送货地址
            {
                string splistid = Validation.ToString(this.tbSummary.GetValue("splistid"));
                if (string.IsNullOrEmpty(splistid))
                {
                    MessageBox.Show("请先选择门店！", "提示");
                    this.tbSummary.Focus("shopcode");
                    return false;
                }

                where = string.Format("status = '01' AND slistid = '{0}' AND plistid = '{1}' ",
                    Validation.ToString(this.tbSummary.GetValue("sellerid")), splistid);
            }
            else if ("stocode" == name)
            {
                where = string.Format("statuscode = '1' {0}",
                        Context.GetAppKeyWhere("usercode", true));
            }

            return true;
        }

        public override void AfterPopWin(string name, System.Collections.Hashtable data, bool ischange)
        {
            if (ischange)
            {
                if ("sellercode" == name)
                {
                    this.tbSummary.SetValue("splistid", "");
                    this.tbSummary.SetValue("shopcode", "");
                    this.tbSummary.SetValue("shopname", "");
                    this.tbSummary.SetValue("comcode", "");
                    this.tbSummary.SetValue("comname", "");
                    this.tbSummary.SetValue("tranday", "0");
                    this.tbSummary.SetValue("tlistid", "");
                    this.tbSummary.SetValue("addcode", "");
                    this.tbSummary.SetValue("addname", "");
                }
                else if ("shopcode" == name)
                {
                    this.tbSummary.SetValue("comcode", "");
                    this.tbSummary.SetValue("comname", "");
                    this.tbSummary.SetValue("tlistid", "");
                    this.tbSummary.SetValue("addcode", "");
                    this.tbSummary.SetValue("addname", "");

                    //计算应发货日期
                    int tranday = Validation.ToInt(this.tbSummary.GetValue("tranday"));
                    DateTime ordate = Convert.ToDateTime(this.tbSummary.GetValue("bookdate"));
                    this.tbSummary.SetValue("reqdate", ordate.AddDays(tranday).ToShortDateString());

                    txtSellDocno_ValueChanged(null, null);//重新验证销售商单号

                    //如果对应的门店是设置是直接出库，那么将仓库设置为必填。
                    var shopid = Validation.ToString(this.tbSummary.GetValue("splistid"));
                    var isEmptyShop = string.IsNullOrEmpty(shopid);
                    if (isEmptyShop)
                    {
                        this.tbSummary.SetValue("stocode", null);
                        this.tbSummary.SetValue("stoname", null);
                        this.tbSummary.SetValue("storageid", null);
                        this.tbSummary.SetRequie("stocode", false);
                        this.tbSummary.Refresh();
                    }
                    else
                    {
                        var dirctStock = UI.Lib.Set.ShopSetting.DirectStock(shopid) == true;

                        this.tbSummary.SetRequie("stocode", dirctStock);
                        this.tbSummary.Refresh();
                    }

                    _lastShopId = shopid;
                }
            }
        }

        private string _lastShopId = string.Empty;

        protected override void AfterCreateSummaryControl(string name, Control c)
        {
            if ("bookdate" == name) //给日期控件添加一个事件
            {
                DateTimePicker dp = c as DateTimePicker;
                dp.ValueChanged += new EventHandler(dp_ValueChanged);
            }
            else if ("selldocno" == name) //验证销售单号是否存在
            {
                TextBoxX txtSellDocno = c as TextBoxX;
                txtSellDocno.ValueChanged += new TextBoxX.DgValueChanged(txtSellDocno_ValueChanged);
            }
            else if ("agio" == name)
            {
                Button btn = c as Button;
                //当前状态为新增或修改时，由于没有计算费用，所以只能预览费用
                btn.Text = ("A" == Action || "M" == Action) ? "预览折扣" : "查看折扣";
                btn.Click += new EventHandler(btn_Click);
            }
        }

        //折扣详情点击时发生
        void btn_Click(object sender, EventArgs e)
        {
            string sellerid = "";
            string comcode = "";
            string status = Validation.ToString(this.tbSummary.GetValue("audstatus")); //审核状态
            if ("1" == status)
            {
                sellerid = Validation.ToString(this.tbSummary.GetValue("sellerid"));
                if (string.IsNullOrEmpty(sellerid))
                {
                    MessageBox.Show("请选择销售商！", "提示");
                    this.tbSummary.Focus("sellercode");
                    return;
                }

                comcode = Validation.ToString(this.tbSummary.GetValue("comcode"));
                if (string.IsNullOrEmpty(comcode))
                {
                    MessageBox.Show("请选择公司代码！", "提示");
                    this.tbSummary.Focus("comcode");
                    return;
                }
            }

            FrmOrd3a02Medit mmid = new FrmOrd3a02Medit(this.ModuleCode, this.Action,
                ("A" == Action || "M" == Action) ? "预览折扣" : "查看折扣",
                (
                    "1" == status ?
                    "" : Validation.ToString(this.tbSummary.GetValue("listid"))
                ),
                Validation.ToDouble(this.tbSummary.GetValue("ordamt")), sellerid, comcode);

            mmid.ShowDialog();
        }

        /// <summary>
        /// 销售单号改变时，验证其存在性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void txtSellDocno_ValueChanged(object sender, EventArgs e)
        {
            //连接数据库，验证存在性
            if (("A" == this.Action || "M" == this.Action) && this.isLoadOk)
            {
                string selldocno = Validation.ToString(this.tbSummary.GetValue("selldocno"));
                if (string.IsNullOrEmpty(selldocno)) return;

                System.Collections.Hashtable hs = new System.Collections.Hashtable();
                hs["listid"] = this.tbSummary.GetValue("listid");
                hs["muser"] = UI.Lib.Context.Comocde;
                hs["splistid"] = this.tbSummary.GetValue("splistid");
                hs["selldocno"] = selldocno;
                string reflt = UI.Lib.Factory.CommonHelper.Entity.ExecFunScalar("checkselldocno", hs);
                if (!string.IsNullOrEmpty(reflt))
                {
                    MessageBox.Show("当前销售商单号重复，请重新录入！", "提示");
                    if (null == sender) this.tbSummary.ClearItem("selldocno");
                    else ((TextBoxX)sender).Revocation(); //重置
                }
            }
        }

        void dp_ValueChanged(object sender, EventArgs e)
        {
            //计算应发货日期
            int tranday = Validation.ToInt(this.tbSummary.GetValue("tranday"));
            DateTime ordate = Convert.ToDateTime(this.tbSummary.GetValue("bookdate"));
            this.tbSummary.SetValue("reqdate", ordate.AddDays(tranday).ToShortDateString());
        }

        //加载修改数据
        private void LoadData()
        {
            base.LoadEditData(null, string.Format(" a.listid ='{0}' ", this.Key));
            base.LoadDtlData(null, string.Format(" a.plistid ='{0}' ", this.Key));

            var gainpct = Validation.ToDouble(this.tbSummary.GetValue("gainpct"));
            this.tbSummary.SetValue("gainpct", gainpct.ToString("0.00%")); //毛利率格式化
        }

        protected override void AfterGridEndEdit(string colName, DataGridViewCellEventArgs e)
        {
            if ("ordqty" == colName || "ordprice" == colName) //修改完订货数量，计算总额
            {
                double price = Validation.ToDouble(this.dgvDtl.GetValue("ordprice")); //价格
                double ordqty = Validation.ToDouble(this.dgvDtl.GetValue("ordqty")); //订货数量
                double all = price * ordqty; //还要算上税率

                //税额
                this.dgvDtl.SetValue("cessamt", all * Validation.ToDouble(this.dgvDtl.GetValue("cess")));
                this.dgvDtl.SetValue("ordamt", all);
            }
        }

        protected override void AfterDtlValueChanged(string name, object value)
        {
            if ("ordamt" == name) //订单总额变化后更新概要的订单总额
            {
                double[] sum = CalcDtlAmt();
                this.tbSummary.SetValue("ordamt", sum[0]);
                this.tbSummary.SetValue("dutyamt", sum[1]);

                CalcGainamt(); //计算毛利总额
            }
            else if ("ordqty" == name)
            {
                double bordqty = Validation.ToDouble(this.dgvDtl.GetValue("bordqty"));
                double now = Validation.ToDouble(value);
                if (bordqty == 0 || 0 == now) return;

                //订货数及赠品数按收到的订单手工输入，订货量不是起订量的倍数提示用户；				
                if (now % bordqty != 0)
                {
                    if (MessageBox.Show("订货数量不是起订数量的整数倍，是否确认?", "提示", MessageBoxButtons.YesNo) ==
                         DialogResult.No)
                    {
                        this.dgvDtl.SetValue("ordqty", "0");
                    }
                }
            }
        }

        private double[] CalcDtlAmt()
        {
            double sum = 0;
            double sumcessamt = 0;
            foreach (DataGridViewRow dr in this.dgvDtl.Rows)
            {
                sum += Validation.ToDouble(dr.Cells["ordamt"].Value);
                sumcessamt += Validation.ToDouble(dr.Cells["cessamt"].Value);
            }

            return new double[] { sum, sumcessamt };
        }

        protected override bool Check()
        {
            if ("P" == Action) //审核时验证价格
            {
                //检查发货仓库
                //如果当前页面上的仓库为空，则必须填写，否则不允许填写
                string storageid = Validation.ToString(this.tbSummary.GetValue("storageid"));
                if (string.IsNullOrEmpty(storageid))
                {
                    MessageBox.Show("[发货仓库]不能为空！", " 提示");
                    this.tbSummary.Focus("stocode");
                    return false;
                }

                //验证价格
                DataTable dt = CommonHelper.Entity.ExecFun("ord3a00_checkPrice", new KeyValuePair<string, object>("plistid", this.Key));

                if (dt == null || 0 == dt.Rows.Count) return true;

                StringBuilder sb = new StringBuilder();
                foreach (DataRow dr in dt.Rows)
                {
                    if (0 != sb.Length) sb.Append(",");

                    sb.Append(dr["pname"]);
                }

                return MessageBox.Show(string.Format("该订单中货号『{0}』的订购价与系统出货价不一致，是否继续审核？", sb.ToString()),
                     "提示", MessageBoxButtons.YesNo) == DialogResult.Yes;
            }

            return true;
        }

        public override void AfterDtlPopWin(string name, System.Collections.Hashtable data, bool ischange)
        {
            if ("productcode" == name)
            {
                this.dgvDtl.Focus("ordqty"); //让订单数量获得焦点
            }
        }

        //计算毛利
        protected void CalcGainamt()
        {
            decimal sum = 0;
            foreach (DataGridViewRow dr in this.dgvDtl.Rows)
            {
                //成本 × 订单数量
                sum += Validation.ToFloat(dr.Cells["pamt"].Value) * Validation.ToFloat(dr.Cells["ordqty"].Value);
            }

            var ordamt = Validation.ToFloat(this.tbSummary.GetValue("ordamt")); //订单总额
            var gainamt = Validation.ToDouble(ordamt - sum, 3);
            this.tbSummary.SetValue("gainamt", gainamt); //毛利总额 = 订单总额 - sum(成本 × 订单数量)

            var gainamtDcm = Validation.ToFloat(gainamt);
            var gainct = "100%";
            if (ordamt != 0)
            {
                gainct = Validation.ToDouble(gainamtDcm / ordamt, 3).ToString("0.00%");
            }

            this.tbSummary.SetValue("gainpct", gainct); //毛利率
        }
    }
}
